"use strict";
angular.module("app.common.services", [])
    .factory('$commons', function ($http, $timeout) {
        var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
        return {
            trim: function (text) {
                return text == null ? "" : ( text + "" ).replace(rtrim, "");
            },
            setValue: function (root, name, value) {
                if (root) {
                    if (name) {
                        if (name.indexOf('[') == 0) {
                            var end = name.indexOf(']'), pname = name.substring(2, end - 1), cname = name.substring(end + 1);
                            cname.substring(0, 1) == '.' && (cname = cname.substring(1));
                            return this.setValue(root[pname], cname, value);
                        } else if (name.indexOf('.') > name.indexOf('[')) {
                            var index = name.indexOf('.'), pname = name.substring(0, index), cname = name.substring(index);
                            cname.substring(0, 1) == '.' && (cname = cname.substring(1));
                            return this.setValue(root[pname], cname, value);
                        } else if (name.indexOf('[') > name.indexOf('.')) {
                            var index = name.indexOf('['), pname = name.substring(0, index), cname = name.substring(index);
                            return this.setValue(root[pname], cname, value);
                        } else {
                            root[name] = value;
                        }
                    }
                }
            },
            getValue: function (root, name) {
                if (root) {
                    if (name) {
                        if (name.indexOf('[') == 0) {
                            var end = name.indexOf(']'), pname = name.substring(2, end - 1), cname = name.substring(end + 1);
                            cname.substring(0, 1) == '.' && (cname = cname.substring(1));
                            return this.getValue(root[pname], cname);
                        } else if (name.indexOf('.') > name.indexOf('[')) {
                            var index = name.indexOf('.'), pname = name.substring(0, index), cname = name.substring(index);
                            cname.substring(0, 1) == '.' && (cname = cname.substring(1));
                            return this.getValue(root[pname], cname);
                        } else if (name.indexOf('[') > name.indexOf('.')) {
                            var index = name.indexOf('['), pname = name.substring(0, index), cname = name.substring(index);
                            return this.getValue(root[pname], cname);
                        } else {
                            return root[name];
                        }
                    }
//    			return root;
                }
            }
        };
    })
    .directive('bcImageUpload', function ($timeout, $commons) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                var attr = $commons.trim(attrs['bcImageUpload']), options = attr && attr.indexOf('{') == 0 ? eval('(' + attr + ')') : $commons.getValue(scope, attr);
                var width = options.width, height = options.height;
                element.bind('change', function (event) {
                    console.log('enter change method..');
                    var image = event.currentTarget.files[0];
                    if (image) {
                        if((image.size/1024/1024).toFixed(2) > 20){
                            alert("请选择20M以内的文件上传!");
                            return;
                        }
                        var reader = new FileReader();
                        reader.onload = function (event) {
                            scope.$apply(function () {
                                console.log('enter reader onload..');
                                scope[options.preview] = event.target.result;
                            });
                        };
                        reader.readAsDataURL(image);
                        var avFile = new AV.File(image.name, image);
                        console.log('begin to call avfile save()..');
                        avFile.save({
                            onprogress:function (e)  {
                                scope[options.progressPercent] = parseInt(e.percent);
                                jQuery('.progress-bar').css('width',scope[options.progressPercent]+'%');
                                scope.$apply();
                                // { loaded: 1234, total: 2468, percent: 50 }
                            }
                        },{}).then(function () {
                            var imageUrl = avFile.attributes.url;
                            if (!!width && !!height) {
                                imageUrl = avFile.thumbnailURL(width, height);
                            }
                            $commons.setValue(scope, options.model, imageUrl);
                            if (options.callbackFunc) {

                                if (scope.$parent[options.callbackFunc]) {
                                    scope.$parent[options.callbackFunc]();
                                }
                                else if (scope[options.callbackFunc]) {
                                    scope[options.callbackFunc]();
                                }

                            }
                            console.log('after avfile save()');

                        }, function (error) {
                            alert('上传失败: ' + error.message);
                        });
                    }
                })
            }
        };
    })



